package com.xmutca.rabbitmq.demo2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerTest {

    public static final String QUENE_NAME = "queue_demo2";
    public static final String IP_ADDRESS = "127.0.0.1";
    public static final String USERNAME = "guest";
    public static final String PASSWORD = "guest";
    public static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 设置rabbitmq的各种信息
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(USERNAME);
        factory.setPort(PORT);
        factory.setPassword(PASSWORD);
        factory.setHost(IP_ADDRESS);

        // 2. 获取连接
        Connection conn = factory.newConnection();

        // 3. 创建通道
        final Channel channel = conn.createChannel();
        channel.basicQos(64);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(consumerTag + "receive message:" + new String(body));
                System.out.println(properties);
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        // 4. 消费者关联
        channel.basicConsume(QUENE_NAME, false, consumer);

        // 5. 连接关闭
      //  channel.close();
       // conn.close();
    }
}
